package com.app.shell.view.mediators
{
	import com.app.common.GlobalConstants;
	import com.app.shell.message.INotification;
	import com.app.shell.message.ShellMessage;
	import com.app.shell.model.ActiveWidgetProxy;
	import com.app.shell.view.components.WidgetHolderView;
	
	import mx.core.IVisualElement;
	import mx.events.FlexEvent;
	
	public class WidgetHolderMediator {
		
		[MessageDispatcher] public var dispatcher:Function;
		
		[Bindable] 
		public var view:WidgetHolderView;

		[Inject]
		[Bindable] public var proxy:ActiveWidgetProxy;
		
		[Observe]
		public function mediateView(view:WidgetHolderView):void {
			trace("Mediator.mediateView() called");
			
			this.view = view;
			
			if (view != null) {
				if (view.initialized) {
					viewInitialized();
				} else {
					view.addEventListener(FlexEvent.CREATION_COMPLETE, componentInitialized);
				}
			}
		}
		
		protected function componentInitialized(e:Event = null):void {
			trace("Mediator.componentInitialized(): View fully initialized, safe to interact");
			viewInitialized();
		}
		
		public function viewInitialized():void {
			trace("Mediator.init(): Initializing view");
			//view.update_btn.addEventListener(MouseEvent.CLICK, updateClicked);
			//view.cancel_btn.addEventListener(MouseEvent.CLICK, cancelClicked);
		}
		
		[MessageHandler(selector='widgetCreated')]
		public function respondToWidgetCreated(message:INotification):void
		{
			// Remove all the widgets from the widget holder and add the new widget requested
			view.removeAllElements();
			view.addElement(proxy.getWidget((message as ShellMessage).note as String) as IVisualElement);
		}
		
		[MessageHandler(selector='shutdownWidgetComplete')]
		public function respondToShutdownWidgetComplete(message:INotification):void
		{
			view.removeElement(proxy.getWidget((message as ShellMessage).note as String));
			dispatcher(new ShellMessage(GlobalConstants.REMOVE_WIDGET_COMPLETE, (message as ShellMessage).note));
		}
		
	}
}